﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Data.ConnectionUI;
using PCCardM.Basic;
using PCCardM.BLL;
using PCCardM.Model;
using PCCardM.UIControl;

namespace PCCardN
{
    public partial class FrmLogin : Form
    {
        public FrmLogin()
        {
            InitializeComponent();
           
        }
       
        string ConnStr;//记录上次连接状态
        private bool _LoginSuccess;

        private void butOK_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(TxtUserName.Text.Trim()))
            {
                MessageBoxInfo.ShowMessage("用户名为空...", MessageClass.Exclamation);
                TxtUserName.Focus();
                return;
            }
            string strUserName = TxtUserName.Text.Trim();
            if (string.IsNullOrEmpty(TxtUserPwd.Text.Trim()))
            {
                MessageBoxInfo.ShowMessage("用户密码为空...", MessageClass.Exclamation);
                TxtUserPwd.Focus();
                return;
            }
            string strUserPwd = TxtUserPwd.Text.Trim();
            //校验数据库
            if (!TestDBConnection())
            {
                return;
            }
            DESC desc = new DESC();   //card密码：空：加密后：wdUo+uoxn3hzOlO5To59bA==
                                      //初始化登录用户
            DataTable dt = new DataTable();
            string connString = Properties.Settings.Default.ConnString;
            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "SELECT * FROM[PCCardM60_LY].[dbo].[T_SYS_USER]WHERE UserName = '" + strUserName + "' AND UserPwd = '" + desc.Encrypto(strUserPwd) + "'";
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(dt);
            }
            
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["UserStatus"].ToString() != "0")
                {
                    MessageBoxEx.ShowMessage("当前账号已被禁用,暂不允许登录系统！", MessageKind.Exclamation);
                    return;
                }
                LoginSysUser sysuser = new LoginSysUser();
                sysuser.IsAdmin = Commons.ParseIntValue(dt.Rows[0]["IsAdmin"].ToString());
                //初始化登录用户全局参数
                LoginUser.LoginUserId = dt.Rows[0]["ID"].ToString();
                LoginUser.LoginUserName = dt.Rows[0]["UserName"].ToString();
                LoginUser.RoleID = dt.Rows[0]["RoleID"].ToString();
                LoginUser.RoleName = dt.Rows[0]["UserName"].ToString();
                //添加登录日志
                this.Hide();
                Form1 mainform = new Form1();

                mainform.Show();

                this._LoginSuccess = true;
            }
            else
            {
                MessageBoxEx.ShowMessage("登录用户名或者密码不正确！", MessageKind.Warning);
                //Commons.InsertLog("系统登录：用户 [" + strUserName + "]，时间：[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "],登录失败(登录用户名或者密码不正确)!", 1);
                //添加登录日志
                TxtUserPwd.Focus();
                TxtUserPwd.SelectAll();
            }

        }



        /// <summary>
        /// 测试连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private bool TestDBConnection()
        {
            //是否连接
            bool connected = false;
            SqlConnection conn = new SqlConnection();
            //配置连接字符串
            conn.ConnectionString = Properties.Settings.Default.ConnString;

            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("select name from master..sysdatabases", conn);
                SqlDataReader reader = cmd.ExecuteReader();
                reader.Close();
                conn.Close();
                connected = true;
                this.Cursor = Cursors.Default;
                //MessageBoxEx.ShowMessage("连接测试成功!", MessageKind.Warning);
            }
            catch (InvalidOperationException)
            {
                this.Cursor = Cursors.Default;
                connected = false;
                MessageBoxEx.ShowMessage("无法连接到指定数据库服务器!", MessageKind.Warning);
            }
            catch (SqlException ex)
            {
                this.Cursor = Cursors.Default;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < ex.Errors.Count; i++)
                    sb.Append(ex.Errors[i].Message).Append(Environment.NewLine);
                connected = false;
                //MessageBoxEx.ShowMessage("连接数据库出错：" + Environment.NewLine + sb.ToString(), MessageKind.Warning);
                MessageBoxEx.ShowMessage("连接数据库出错：" + Environment.NewLine + "请重新设置数据库配置...", MessageKind.Warning);
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                connected = false;
                MessageBoxEx.ShowMessage("出现意外错误：" + Environment.NewLine + ex.Message, MessageKind.Warning);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
            }
            return connected;
        }

        public bool LoginSuccess
        {
            get
            {
                return _LoginSuccess;
            }
            set
            {
                _LoginSuccess = value;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Frm_DataBase frm = new Frm_DataBase();
            frm.ShowDialog();
        }
        private string GetStrConnFromDateConnection(DataConnectionDialog theSouceDialog)
        {
           
            if (DatebasConnection(theSouceDialog))
            {
                return theSouceDialog.ConnectionString;
            }
            return null;


        }
        private bool DatebasConnection(DataConnectionDialog theSouceDialog)
        {
            DataSource.AddStandardDataSources(theSouceDialog);
            theSouceDialog.SelectedDataSource = DataSource.SqlDataSource;
            theSouceDialog.SelectedDataProvider = DataProvider.SqlDataProvider;
            if (!string.IsNullOrEmpty(this.ConnStr))
            {
                theSouceDialog.ConnectionString = this.ConnStr;
            }
            else
            {
                theSouceDialog.ConnectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Password=Rfid2022;Data Source=.";
            }

            bool rlt = false;
            if (DataConnectionDialog.Show(theSouceDialog) == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    string newStr = theSouceDialog.ConnectionString;
                    using (SqlConnection conn = new SqlConnection(newStr))
                    {
                        conn.Open();
                        rlt = true;
                        this.ConnStr = newStr;
                        conn.Close();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return rlt;
        }
        private void butExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmLogin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.butOK_Click(sender, e);
            }
        }
    }
}

